package az.mecid.rssreader.cron.servlets;

import az.mecid.rssreader.model.entity.FeedEntity;
import az.mecid.rssreader.model.utils.EMF;
import com.google.appengine.api.labs.taskqueue.Queue;
import com.google.appengine.api.labs.taskqueue.QueueFactory;
import com.google.appengine.api.labs.taskqueue.TaskOptions;

import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.persistence.Query;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.logging.Logger;

/**
 * Created by IntelliJ IDEA.
 * User: mega
 * Date: 27.02.2010
 * Time: 1:27:05
 */
@SuppressWarnings("unchecked")
public class CronServlet extends HttpServlet{

    private static final Logger logger = Logger.getLogger(CronServlet.class.getName());

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        
        EntityManager em = EMF.get().createEntityManager();
        List<FeedEntity> feeds;
        try {
            Query query = em.createQuery("select e from FeedEntity e order by e.id");
            EntityTransaction transaction = em.getTransaction();
            try{
                transaction.begin();
                feeds = query.getResultList();
                transaction.commit();
            }finally {
                if(transaction.isActive())
                    transaction.rollback();
            }
        } finally {
            em.close();
        }

        Queue queue = QueueFactory.getQueue("FeedManagerQueue");
        for (FeedEntity feed : feeds){
            queue.add(TaskOptions.Builder
                    .url("/worker/feedupdate")
                    .param("id",feed.getId().toString())
            );
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req,resp);
    }
}
